package com.stxx.stiot2.auth2.topiam;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.stxx.stiot2.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import org.noear.solon.Solon;


/**
 * TopIAM 认证请求 duan'l
 *
 * @author xlsea
 * @since 2024-01-06
 */
@Slf4j
public class AuthMaxKeyRequest extends AuthDefaultRequest {


    /**
     * 设定归属域
     */
    public AuthMaxKeyRequest(AuthConfig config) {
        super(config, getAuthSource());
    }

    public AuthMaxKeyRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, getAuthSource(), authStateCache);
    }

    @Override
    public AuthToken getAccessToken(AuthCallback authCallback) {

        String body = doPostAuthorizationCode(authCallback.getCode());
        JSONObject object = JSONObject.parseObject(body);
        // oauth/token 验证异常
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("error_description"));
        }
        // user 验证异常
        if (object.containsKey("message")) {
            throw new AuthException(object.getString("message"));
        }
        return AuthToken.builder()
                .accessToken(object.getString("access_token"))
                .refreshToken(object.getString("refresh_token"))
                .idToken(object.getString("id_token"))
                .tokenType(object.getString("token_type"))
                .scope(object.getString("scope"))
                .build();
    }

    @Override
    public AuthUser getUserInfo(AuthToken authToken) {
        String body = doGetUserInfo(authToken);
        JSONObject object = JSONObject.parseObject(body);
        // oauth/token 验证异常
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("error_description"));
        }
        // user 验证异常
        if (object.containsKey("message")) {
            throw new AuthException(object.getString("message"));
        }
        return AuthUser.builder()
                .uuid(object.getString("userId"))
                .username(object.getString("username"))
                .nickname(object.getString("displayName"))
                .avatar(object.getString("avatar_url"))
                .blog(object.getString("web_url"))
                .company(object.getString("organization"))
                .location(object.getString("location"))
                .email(object.getString("email"))
                .remark(object.getString("bio"))
                .token(authToken)
                .source(source.toString())
                .build();
    }


    private static AuthSource getAuthSource(){

        SysConfigService configService = Solon.context().getBean(SysConfigService.class);
        JSONObject jsonObject = new JSONObject(configService.getConfig(SysConfigService.Keys.auth_maxkey));
        String url = jsonObject.getString("server_url");
        AuthSource authSource = new AuthSource(){
            /**
             * 授权的api
             */
            @Override
            public String authorize() {
                return url + "/sign/authz/oauth/v20/authorize";
            }

            /**
             * 获取accessToken的api
             */
            @Override
            public String accessToken() {
                return url + "/sign/authz/oauth/v20/token";
            }

            /**
             * 获取用户信息的api
             */
            @Override
            public String userInfo() {
                return url + "/sign/api/oauth/v20/me";
            }

            /**
             * 平台对应的 AuthRequest 实现类，必须继承自 {@link AuthDefaultRequest}
             */
            @Override
            public Class<? extends AuthDefaultRequest> getTargetClass() {
                return AuthMaxKeyRequest.class;
            }


            @Override
            public String toString(){
                return "maxkey";
            }
        };
        return authSource;
    }

}